package com.tiancheng.onecode.configuration;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.tiancheng.onecode.aop.TCAuthRequestInterceptor;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * WebMvcAutoConfiguration
 */
@Configuration
@Order(3)
public class SpringMvcConfiguration implements WebMvcConfigurer {
    @Resource
    private WebMvcProperties mvcProperties;
	@Resource
	private WebProperties webProperties;
    @Resource
    private TCAuthRequestInterceptor authRequestInterceptor;

    /**
     * 日志线程池配置
     *
     * @return {@link Executor}
     */
    @Bean
    public Executor logExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 配置核心线程数
        executor.setCorePoolSize(5);
        // 配置最大线程数
        executor.setMaxPoolSize(5);
        // 配置队列大小
        executor.setQueueCapacity(99999);
        // 配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("async-log-service-");

        // CallerRunsPolicy：超出最大线程数后的任务将进行缓存队列等待，缓存队列所有任务输送给执行队列完毕清空后，新任务进入缓存队列
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 执行初始化
        executor.initialize();
        return executor;
    }
    /**
     * 添加自定义的Converters和Formatters.
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 以下自定义的转换只适用于url传递参数
        registry.addConverter(new StringToLocalDateConverter());
        registry.addConverter(new StringToLocalDateTimeConverter());
    }

    /**
     * 因为拦截器或者过滤器的原因,导致spring.resourcesstatic-locations和spring.mvc.static-path-pattern配置无效，无法访问静态资源,需要重写次方法实现静态资源的访问
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(this.mvcProperties.getStaticPathPattern()).addResourceLocations(this.webProperties.getResources().getStaticLocations());
        //swagger相关
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //registry.addInterceptor(new ControllerInterceptor()).addPathPatterns("/**").order(-999);
        registry.addInterceptor(authRequestInterceptor)
                .addPathPatterns("/admin/**","/api/**","/common/**")      // 只拦截路径为 "/api/**" 的请求
//                .excludePathPatterns("/api/public/**") // 排除路径为 "/api/public/**" 的请求
        ;
    }

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
        return (factory -> {
            ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/fe/index.html");
            factory.addErrorPages(errorPage404);
        });
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        //接收参数下划线转为驼峰
        //argumentResolvers.add(underlineToCamelArgumentResolver);
    }


    @Bean
    @Primary
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        // 通过该方法对mapper对象进行设置，所有序列化的对象都将按改规则进行系列化
        // Include.Include.ALWAYS 默认
        // Include.NON_DEFAULT 属性为默认值不序列化
        // Include.NON_EMPTY 属性为 空（""） 或者为 NULL 都不序列化，则返回的json是没有这个字段的。这样对移动端会更省流量
        // Include.NON_NULL 属性为NULL 不序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 允许出现特殊字符和转义符
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        // 允许出现单引号
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);

        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addDeserializer(LocalDate.class, JsonLocalDateFormatter.buildDeserializer());
        simpleModule.addSerializer(LocalDate.class, JsonLocalDateFormatter.buildSerializer());
        simpleModule.addDeserializer(LocalDateTime.class, JsonLocalDateTimeFormatter.buildDeserializer());
        simpleModule.addSerializer(LocalDateTime.class, JsonLocalDateTimeFormatter.buildSerializer());
        simpleModule.addDeserializer(Long.class, JsonLongFormatter.buildDeserializer());
        simpleModule.addSerializer(Long.class, JsonLongFormatter.buildSerializer());

        // 注册自定义反序列化, 适用于json传递参数
        objectMapper.registerModule(simpleModule);
        //objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);//驼峰统一返回下划线

        return objectMapper;
    }
//
//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        // 允许跨域
//        registry.addMapping("/**")
//                .allowedOrigins("*")
//                .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
//                .allowCredentials(true).maxAge(3600);
//
//    }

}